
# -*- coding: utf-8 -*-
import os
import time
import random
import PathConfig
import re
import csv


# 正则查找替换中文字符串



# 排重
csvKeyList = []
csvList = []

# 导出新增未本地化的字符 1 , 其他表示全部.
outputType = 1

# 已有的本地化信息
oldLSKeyList = []

def csvWrite():
	# csv文件读写
	csvFile = open(PathConfig.localstring_csv_filepath, 'w')
	csv_writer = csv.writer(csvFile)

	csv_writer.writerow(['localstringKey','1'])
	csv_writer.writerow(['语言','中文'])
	
	for csvDic in csvList:
		key = csvDic['key']
		value = csvDic['value']
		csv_writer.writerow([key,value])

	csvFile.close()


def replaceStr(content, oldstr, newstr):

	replacements = {oldstr:newstr}
	for src, target in replacements.iteritems():
			content = content.replace(src, target)

	return content



def traverse(file_dir):
	

	fs = os.listdir(file_dir)
	for dir in fs:
		if dir.startswith('.'):
			#过滤隐藏
			continue

		tmp_path = os.path.join(file_dir, dir)
		if not os.path.isdir(tmp_path):

			if dir.startswith('AX'):
				continue
			if not dir.endswith('.h') and not dir.endswith('.m'):
				continue

			with open(tmp_path) as f:
				file_str = f.read()
				
				content = file_str.decode('utf-8')

				if outputType == 1:
					# if oldLSKeyList
					patls = u'(LS\\(@"[^"]*[\u4E00-\u9FA5]+[^"\n]*?"\\))'
					resultls = re.findall(patls,content)
					for s_ls in resultls:
						sn_str = s_ls.encode('utf-8')
						oldLSKeyList.append(sn_str)


				pat = u'(@"[^"]*[\u4E00-\u9FA5]+[^"\n]*?")'
				results = re.findall(pat,content)
				for s in results:
				    sn_str = s.encode('utf-8')
				    new_sn_str = 'LS(%s)'%(sn_str)

				    if new_sn_str in oldLSKeyList:
				    	continue

				    # 字符串替换
				    file_str = file_str.replace(new_sn_str,sn_str)
				    file_str = file_str.replace(sn_str,new_sn_str)

				    sn_s = sn_str[2:-1]

				    if sn_s not in csvKeyList:
				    	csvKeyList.append(sn_s)
				    	csvList.append({'key':sn_s,'value':sn_s})

				    print '"%s" = "%s";' % (sn_s,sn_s)

			with open(tmp_path, 'w') as f:
				f.write(file_str)

		else:
			# 是文件夹,则递归调用
			traverse(tmp_path)




def cleanLS(file_dir):
	

	fs = os.listdir(file_dir)
	for dir in fs:
		if dir.startswith('.'):
			#过滤隐藏
			continue

		tmp_path = os.path.join(file_dir, dir)
		if not os.path.isdir(tmp_path):

			if dir.startswith('AX'):
				continue
			if not dir.endswith('.h') and not dir.endswith('.m'):
				continue

			with open(tmp_path) as f:
				file_str = f.read()
				
				content = file_str.decode('utf-8')

				pat = u'(@"[^"]*[\u4E00-\u9FA5]+[^"\n]*?")'
				results = re.findall(pat,content)
				for s in results:
				    sn_str = s.encode('utf-8')
				    new_sn_str = 'LS(%s)'%(sn_str)

				    # 字符串替换
				    file_str = file_str.replace(new_sn_str,sn_str)

			with open(tmp_path, 'w') as f:
				f.write(file_str)

		else:
			# 是文件夹,则递归调用
			cleanLS(tmp_path)

def main():

	# traverse(PathConfig.rub_filepath)
	cleanLS(PathConfig.rub_filepath)
	# csvWrite()
	print('Finish done')

if __name__ == '__main__':
	main()









